import React from 'react';
import ComponentExtend from "components/decorated/component-extend";
import {observer} from "mobx-react";
import {observable, action} from 'mobx';
import {Redirect, Route} from "react-router-dom";
import ReactLoading from 'react-loading';
//样式复用，用于loading，如有需要需重建样式文件再导入
import '../state/state.scss';
import {RouterList} from "@/routers/router-list";
import {TokenAuthAction} from "auxiliaries/session/overload/token";


//todo: 将拦截器更改为异步行为 → 以便于有需要远程验证信息, 区分为远程、本地验证，以便节约流量
@observer
class AuthenticRoute extends ComponentExtend {
    @observable authState = "before";

    @action
    async componentDidMount() {
        super.componentDidMount();

        let token = await TokenAuthAction.GetToken();
        if (!token) {
            setTimeout(() => {
                this.authState = 'relink';
            }, 200);
        } else {
            //考虑是否需要远程验证一波，不过会挺吃资源的
            this.authState = 'access';
        }
    }

    render() {

        switch (this.authState) {
            case 'before':
                return (
                    <div className={"before loading"}>
                        <div className="box">
                            <ReactLoading type={'spokes'} color="#000"/>
                            <span>正在获取相关信息...</span>
                        </div>
                    </div>
                );
            case 'auth-ing':
                return (
                    <div className={"auth-ing loading"}>
                        <div className="box">
                            <ReactLoading type={'spokes'} color="#000"/>
                            <span>正在验证...</span>
                        </div>
                    </div>
                );
            //通过
            case 'access':
                return <Route {...this.props}/>;
            //转跳
            case 'relink':
                let {pathname, search} = this.props.location;
                return <Redirect to={RouterList.account.login(`${pathname + search}`)}/>;
            default:
                return null;
        }
    }
}

export default AuthenticRoute;